<div style="padding:8px 8px 0 4px;font-weight: bold;"><i class="am-icon-home am-icon-shopping-bag" style="margin-right:12px;"></i>升级包管理</div>
<!-- 查询区 -->
<div id="searchContainer"></div>
<div class="row1 up_row">
    <div class="data_container">
        <!-- 按钮区 -->
        <div id="buttonsDiv">
            <button type="button" id="newPackage" class="am-btn am-btn-primary am-radius am-btn-xs">新增升级包</button>
            <button type="button" id="toBatchUpPackage" class="am-btn am-btn-success am-radius am-btn-xs">批量修改升级包</button>
            <button type="button" id="toUpdateTestStatu" class="am-btn am-btn-warning am-radius am-btn-xs">更新测试状态</button>
            <button type="button" id="toUpdateTestResult" style="display:none;" class="am-btn am-btn-warning am-radius am-btn-xs">更新测试结果</button>
        </div>
        <!-- 数据列表区 -->
        <div id="contentDiv" class="content_div"></div>
    </div>
</div>
<script src="/public/js/timeago/timeago.min.js"></script>
<script>
$(function() {
    if (window.UG_isTester === '1') {
        $('#toUpdateTestResult').show();
    }

    // 加载查询区
    var searchBar = new SearchBar({
        containerId: "searchContainer",
        textPlaceholder: '查询条件：模块名、升级包名、升级内容',
        queryList: [
            { title: "升级项目", key: "packageProjectId", url: "/select/getUpgradeProjects?key=packageProjectId", forSort: 10 },
            { title: "责任人", key: "leader_userid", url: "/select/getDevelopers?key=leader_userid", forSort: 12 },
            { title: "测试状态", key: "test_status", url: "/select/getTestStatus?key=test_status" },
            { title: "是否发布", key: "confirm_publish", data: { key: "confirm_publish", datas: [{ code: "1", name: "是" }, { code: "0", name: "否" }] } }
        ],
        queryFunc: function() { load(); }
    });
    searchBar.render();

    // 加载表格
    var workGrid = new WorkGrid({
        url: '/simpleUpgradePackage/query',
        searchBar: searchBar,
        checkbox: true,
        checkboxProperty: "id",
        columns: [
            { display: "模块", property: "module", sort: "module", width: "7%" },
            {
                display: "描述",
                property: "description",
                sort: "description",
                view: function(col) {
                    return '(' + col.name + ') ' + noHighlight(col.description) + '&nbsp;<span style="color:#EF971C;font-weight:bold;">' + (col.special_remark || '') + '</span>';
                }
            },
            {
                display: "备注",
                width: "6%",
                view: function(col) {
                    var html = '';
                    html += (html !== '' ? ' ' : '') + (col.is_need_reboot === 1 ? '<span style="color:#ec5656">重启</span>' : '');
                    html += (html !== '' ? ' ' : '') + (col.is_need_clearcache === 1 ? '<span style="color:#ec5656">清除缓存</span>' : '');
                    html += (html !== '' ? ' ' : '') + (col.is_need_delfile === 1 ? '<span style="color:#ec5656">删除文件</span>' : '');
                    html += (html !== '' ? ' ' : '') + (col.is_need_exescript === 1 ? '<span style="color:#ec5656">手动执行脚本</span>' : '');
                    return html;
                }
            },
            { display: "责任人", property: "leader_username", sort: "leader_username", width: "5%" },
            {
                display: "创建时间",
                sort: "create_time",
                width: "6%",
                view: '<div class="need_to_be_rendered" role="tip" tip="{{create_time_display}}" datetime="{{create_time_display}}"></div>'
            }, {
                display: "绑定项目",
                width: "5%",
                view: function(col) {
                    var _bind_projects = col.bind_projects || '';
                    var c = _bind_projects !== '' ? _bind_projects.split(',').length : 0;
                    //return '<span class="am-badge ' + (c > 0 ? 'am-badge-secondary' : '') + ' am-round" role="tip" tip="' + _bind_projects + '">' + c + '</span>';

                    return '<span class="am-badge am-round" role-bdxm="' + col.id + '" role="tip" tip=""></span>';
                }
            },
            {
                display: "测试状态",
                width: "6%",
                view: function(col) {
                    if (col.test_status === '99') {
                        return '<a role="tip" tip="' + col.test_username + ' - ' + col.test_time_display + '" class="am-badge am-badge-success am-round">' + col.test_status_display + '</a>';
                    } else if (col.test_status === '-1') {
                        return '<a role="tip" tip="' + col.test_username + ' - ' + col.test_time_display + '" class="am-badge am-badge-warning am-round">' + col.test_status_display + '</a>';
                    } else if (col.test_status === '1') {
                        return '<a role="tip" tip="' + col.test_username + ' - ' + col.test_time_display + '" class="am-badge am-badge-secondary am-round">' + col.test_status_display + '</a>';
                    }
                    return '<a class="am-badge am-round">' + (col.test_status_display || '') + '</a>';
                }
            },
            {
                display: "测试结果",
                width: "6%",
                view: function(col) {
                    var _tip = '需求点数：' + strOf(col.demand_point_count) + '<br>';
                    _tip += '缺陷数：' + strOf(col.defect_count) + '<br>';
                    _tip += '高缺陷数：' + strOf(col.high_defect_count) + '<br>';
                    _tip += '返工次数：' + strOf(col.rework_count);
                    return '<span role="tip" tip="'+ _tip +'">' + strOf(col.demand_point_count) + '/' + strOf(col.defect_count) + '/' + strOf(col.high_defect_count) + '/' + strOf(col.rework_count) + '</span>';
                }
            },
            {
                display: "是否发布",
                sort: "is_publish",
                width: "5%",
                view: function(col) {
                    if (col.is_publish === 1) {
                        return '<a role="tip" tip="' + col.publish_username + ' - ' + col.publish_time_display + '" class="am-badge am-badge-success am-round">是</a>';
                    } else {
                        return '<a class="am-badge am-round">否</a>';
                    }
                }
            }, {
                display: "操作",
                width: "220px",
                view: function(col) {
                    var view = '';

                    view += '<button type="button" data-id="' + col.id + '" data-action="toBindProject" class="am-btn am-btn-primary am-btn-mini am-radius">绑定项目</button>&nbsp;';

                    view += '<button type="button" data-id="' + col.id + '" data-action="remove" class="am-btn am-btn-danger am-btn-mini am-radius">删除</button>&nbsp;';

                    if (col.is_publish === 0) {
                        view += '<button type="button" data-id="' + col.id + '" data-action="publish" class="am-btn am-btn-success am-btn-mini am-radius">发布</button>&nbsp;';
                    }

                    view += '<button type="button" data-id="' + col.id + '" data-action="downloadZipFile" class="am-btn am-btn-secondary am-btn-mini am-radius">下载</button>';
                    return view;
                }
            }
        ],
        loadAfterListener: function() {
            // 格式化创建时间的格式
            timeago().render(document.querySelectorAll('.need_to_be_rendered'), 'zh_CN');

            var _packageIds = '';
            for (var i = 0; i < workGrid.tmpDatas.length; i++) {
                if (_packageIds !== '') {
                    _packageIds += ',';
                }
                _packageIds += '\'' + workGrid.tmpDatas[i].id + '\'';
            }

            // 加载升级包关联的项目信息
            common.doAjax('/simpleUpgradePackage/queryPackageProjects', { packageIds: _packageIds }).done(function(data) {
                var datas = data.datas;
                for (var i = 0; i < workGrid.tmpDatas.length; i++) {
                    var names = '';
                    for (var j = 0; j < datas.length; j++) {
                        if (datas[j].package_id === workGrid.tmpDatas[i].id) {
                            if (names !== '') {
                                names += ',';
                            }
                            names += datas[j].name;
                        }
                    }

                    var c = names !== '' ? names.split(',').length : 0;
                    var _class = (c > 0 ? 'am-badge-secondary' : '');

                    $('[role-bdxm="' + workGrid.tmpDatas[i].id + '"]').addClass(_class).attr('tip', names).html(c);
                }
            });


            // 绑定提示
            $('[role="tip"]').mouseover(function() {
                var _this = $(this);
                _this.justToolsTip({
                    animation: "moveInTop",
                    contents: _this.attr('tip') || '',
                    gravity: 'top'
                });
            });

            // 绑定项目
            $('#contentDiv [data-action="toBindProject"]').click(function() {
                var id = $(this).attr('data-id');
                var url = "/simpleUpgradePackage/toBindProject?id=" + id + "&_=" + new Date().getTime();
                zeroModal.show({ url: url, title: '绑定项目', width: '700px', height: '400px', onClosed: function() { workGrid.load(); } });
            });

            // 发布
            $('#contentDiv [data-action="publish"]').click(function() {
                var val = $(this).attr('data-id');

                var projects = $('[role-bdxm="' + val + '"]').attr('tip') || '';
                if (projects === '') {
                    zeroModal.error('请选绑定项目再发布！');
                    return;
                }

                zeroModal.confirm({
                    content: '确认发布升级包吗？',
                    contentDetail: '发布后将不能进行修改，请谨慎操作！',
                    okFn: function() {
                        zeroModal.loading();
                        $.ajax({
                            url: '/simpleUpgradePackage/publish',
                            dataType: "json",
                            type: "post",
                            data: 'id=' + val,
                            success: function(data) {
                                zeroModal.closeAll();
                                if (data.success) {
                                    $.toast({ text: '发布成功！', showHideTransition: 'slide', icon: 'success', position: 'top-center' });
                                } else {
                                    $.toast({ text: '发布失败！', showHideTransition: 'slide', icon: 'error', position: 'top-center' });
                                }
                                load();
                            }
                        });
                    }
                });
            });

            // 删除
            $('#contentDiv [data-action="remove"]').click(function() {
                var val = $(this).attr('data-id');
                zeroModal.confirm({
                    content: '确认删除升级包吗？',
                    contentDetail: '删除后将无法恢复，请谨慎操作！',
                    okFn: function() {
                        zeroModal.loading();
                        $.ajax({
                            url: '/simpleUpgradePackage/remove',
                            dataType: "json",
                            type: "post",
                            data: 'id=' + val,
                            success: function(data) {
                                zeroModal.closeAll();
                                if (data.success) {
                                    $.toast({ text: '删除成功！', showHideTransition: 'slide', icon: 'success', position: 'top-center' });
                                } else {
                                    $.toast({ text: '删除失败！', showHideTransition: 'slide', icon: 'error', position: 'top-center' });
                                }
                                load();
                            }
                        });
                    }
                });
            });

            // 下载
            $('#contentDiv [data-action="downloadZipFile"]').click(function() {
                var id = $(this).attr('data-id');
                window.open('/simpleUpgradePackage/downloadZipFile?id=' + id);
            });
        }
    });
    workGrid.render();

    // 上传
    $('#newPackage').click(function() {
        var url = "/simpleUpgradePackage/toUpload?_=" + new Date().getTime();
        var title = "上传升级包";
        zeroModal.show({ url: url, iframe: true, title: title, width: '800px', height: '70%', onClosed: function() { workGrid.load(); } });
    });

    $('#toBatchUpPackage').click(function() {
        var ids = _bs_getSelectIds('chk_contentDiv');
        if (ids == '') {
            zeroModal.error('请选择记录进行操作！');
            return;
        }
        var url = "/simpleUpgradePackage/toBatchUpPackage?ids=" + ids + "&_=" + new Date().getTime();
        zeroModal.show({ url: url, title: '批量修改升级包', width: '90%', height: '500px', onClosed: function() { workGrid.load(); } });
    });

    $('#toUpdateTestResult').click(function() {
        var ids = _bs_getSelectIds('chk_contentDiv');
        if (ids == '') {
            zeroModal.error('请选择记录进行操作！');
            return;
        }
        var url = "/simpleUpgradePackage/toUpdateTestResult?ids=" + ids + "&_=" + new Date().getTime();
        zeroModal.show({ url: url, title: '批量修改升级包测试结果', width: '80%', height: '50%', onClosed: function() { workGrid.load(); } });
    });

    $('#toUpdateTestStatu').click(function() {
        var ids = _bs_getSelectIds('chk_contentDiv');
        if (ids == '') {
            zeroModal.error('请选择记录进行操作！');
            return;
        }

        zeroModal.show({
            title: '更新测试状态',
            content: '<div id="toUpdateTestStatuDiv"></div>',
            ok: true,
            cancel: true,
            onComplete: function() {
                common.doAjax('/select/getTestStatus', {}, 'get').done(function(data) {
                    var html = '<ul class="am-list am-list-static am-list-border">';
                    for (var i = 0; i < data.datas.length; i++) {
                        html += '  <li data-code="' + data.datas[i].code + '" role="test_status_item" style="font-size:14px;">' + data.datas[i].name + '</li>';
                    }
                    html += '   </ul>';
                    $('#toUpdateTestStatuDiv').html(html);

                    $('[role="test_status_item"]').click(function(e) {
                        var jobj = $(this);

                        $('[role="test_status_item"]').removeClass('ug_checked');
                        $('[role="test_status_item"]').find('.am-icon-check').remove();

                        jobj.append('<i class="am-icon-check" style="margin-left:8px;"></i>').addClass('ug_checked');
                    });
                });
            },
            okFn: function() {
                var checked = $('[role="test_status_item"].ug_checked');
                if (checked.length === 0) {
                    zeroModal.error('请选择状态进行操作！');
                    return false;
                }
                var val = checked.attr('data-code');

                var objs = [];
                var idArrs = ids.split(',');
                for (var i = 0; i < idArrs.length; i++) {
                    objs.push({
                        id: idArrs[i],
                        test_status: val
                    });
                }
                common.doAjax('/simpleUpgradePackage/doUpdateTestStatu', { packagesJson: JSON.stringify(objs) }).done(function() {
                    $.toast({ text: '更新测试状态成功！', showHideTransition: 'slide', icon: 'success', position: 'top-center' });
                    load();
                });
            }
        });

    });

    // 查询
    function load(params) {
        workGrid.load(1, params);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 绑定按钮区事件
    /*$('[btn-action="edit"]').click(function() {
        edit();
    });

    $('[btn-action="mergeDownloadPackage"').click(function() {
        var ids = _bs_getSelectIds("chk_contentDiv");
        if (ids == "") { myUtil.alert("请选择记录进行操作！"); return; }

        var upgradeProjectId = "";
        var datas = workGrid.findDatas("id", ids);
        for (var i = 0; i < datas.length; i++) {
            if (upgradeProjectId != "" && datas[i].upgrade_project_id != upgradeProjectId) {
                myUtil.alert("只能选择同一个项目的升级包进行合并下载操作！");
                return;
            }
            upgradeProjectId = datas[i].upgrade_project_id;
        }
    });*/

    function edit(id) {
        $.confirm({
            content: 'url:/simpleUpgradePackage/edit?id=' + (id || '') + '&_=' + new Date().getTime() + '&' + searchBar.getQueryParams(),
            title: id ? '修改升级包' : '新增升级包',
            columnClass: 'col-md-8 col-md-offset-2',
            confirm: function() {
                if (!$("#myEditForm").valid())
                    return false;

                $.ajax({
                    url: '/simpleUpgradePackage/save',
                    dataType: "json",
                    cache: false,
                    type: "post",
                    data: $('#myEditForm').serialize(),
                    success: function(data) {
                        if (data.success) {
                            myUtil.toast_success("保存成功！");
                        } else {
                            myUtil.toast_failure("保存失败！");
                        }
                        load();
                    }
                });
            }
        });
    }

    function toUpload(id) {
        var data = workGrid.findData("id", id);
        var _title = (data.original_file_path != null ? "查看" : "上传") + "升级包";
        var _url = "url:/simpleUpgradePackage/" + (data.original_file_path != null ? "uploadInfo" : "toUpload");
        var _columnClass = (data.original_file_path != null ? "col-md-10 col-md-offset-1" : "col-md-8 col-md-offset-2");
        window.jc = $.confirm({
            content: _url + '?id=' + (id || '') + '&_=' + new Date().getTime(),
            title: _title,
            columnClass: _columnClass,
            confirmButton: false,
            onClose: function() { load(); }
        });
    }

    function noHighlight(str) {
        if (str === undefined || str === null || str === '') {
            return str;
        }

        var re = /#\d*\s/g;
        var allStr;

        var keywords = [];
        while ((allStr = re.exec(str)) !== null) {
            keywords.push(allStr[0]);
        }
        for (var i = 0; i < keywords.length; i++) {
            str = str.replace(keywords[i], '<font color="#EF971C">' + keywords[i] + '</font>');
        }
        return str;
    }

    function strOf(obj) {
        return obj !== undefined && obj !== null ? obj : '';
    }
});
</script>